# -*- coding: utf-8 -*-
"""
改进说明：
1. 当左右螺纹类型相同时，无论有无弯头，都合并成一个字母，并对尺寸进行从小到大排序。
2. 去除多余的文本说明。
3. 前端美化与用户体验改进。
4. 提交后保留用户选择，避免重置。

运行步骤：
1. pip install flask
2. python app.py
3. 浏览器访问 http://127.0.0.1:5000
"""

from flask import Flask, request, render_template
app = Flask(__name__)

# 下拉选项数据定义
joint_types = [
    ("1", "1外螺纹/外螺纹"),
    ("2", "2外螺纹/活动内螺纹（扣压螺母）"),
    ("3", "3活动内螺纹（扣压螺母）/活动内螺纹（扣压螺母）"),
    ("4", "4外螺纹堵头"),
    ("5", "5衬套（外螺纹/固定内螺纹）"),
    ("6", "6过板接头"),
    ("7", "7固定内螺纹/固定内螺纹（无螺母）"),
    ("8", "8锁母"),
    ("9", "9内螺纹堵头（扣压螺母）")
]

thread_types = [
    ("A", "A 英管螺纹 BSP (BSPP)"),
    ("B", "B 英锥管螺纹 BSPT (BSPT)"),
    ("N", "N 布锥管螺纹 NPT (NPT)"),
    ("J", "J 美制JIC (JIC)"),
    ("F", "F 美制ORFS (ORFS)"),
    ("P", "P 美制SAE (SAE)"),
    ("G", "G 英管螺纹平面、O-Ring密封"),
]

bend_types = [
    ("", "直"),
    ("4", "45°"),
    ("9", "90°")
]

material_types = [
    ("", "碳钢"),
    ("BR", "黄铜"),
    ("SS", "不锈钢")
]

# 螺纹尺寸映射表
thread_size_map = {
    "A": [("02", "G1/8-28"),("04", "G1/4-19"),("06", "G3/8-19"),("08", "G1/2-14"),("10", "G5/8-14"),("12", "G3/4-14"),("16", "G1-11"),("20", "G1 1/4-11"),("24", "G1 1/2-11"),("32", "G2-11")],
    "B": [("02", "R1/8-28"),("04", "R1/4-19"),("06", "R3/8-19"),("08", "R1/2-14"),("10", "R5/8-14"),("12", "R3/4-14"),("16", "R1-11"),("20", "R1 1/4-11"),("24", "R1 1/2-11"),("32", "R2-11")],
    "N": [("02", "Z1/8-27"),("04", "Z1/4-18"),("06", "Z3/8-18"),("08", "Z1/2-14"),("10", "Z5/8-14"),("12", "Z3/4-14"),("16", "Z1-11 5"),("20", "Z1 1/4-11 5"),("24", "Z1 1/2-11 5"),("32", "Z2-11 5")],
    "J": [("04", "7/16-20"),("05", "1/2-20"),("06", "9/16-18"),("08", "3/4-16"),("10", "7/8-14"),("12", "1 1/16-12"),("16", "1 5/16-12"),("20", "1 5/8-12"),("24", "1 7/8-12"),("32", "2 1/2-12")],
    "F": [("04", "9/16-18"),("06", "11/16-16"),("08", "13/16-16"),("10", "1-4"),("12", "1 3/16-12"),("16", "1 7/16-12"),("20", "1 11/16-12"),("24", "2-12")],
    "P": [("06", "5/8-17"),("12", "1 1/16-14")],
    "G": [("02", "G1/8-28"),("04", "G1/4-19"),("06", "G3/8-19"),("08", "G1/2-14"),("10", "G5/8-14"),("12", "G3/4-14"),("16", "G1-11"),("20", "G1 1/4-11"),("24", "G1 1/2-11"),("32", "G2-11")]
}


def process_code(joint_type, bend_type, t_left, s_left, t_right, s_right, material, o_ring):
    # 初始拼接
    raw_code = joint_type + t_left + t_right + (bend_type if bend_type else "") + "-" + s_left + "-" + s_right + material + o_ring

    def extract_details(code_str):
        dash_index = code_str.find("-")
        prefix = code_str[:dash_index]   
        suffix = code_str[dash_index+1:] 

        jt = prefix[0]  
        remain = prefix[1:]  

        # 解析螺纹与弯头
        # remain可能是1~3个字符(不含jt)
        # 情况：无bend_type = 2字符，如BJ；有bend_type=3字符，如BJ4
        if len(remain) == 2:
            tl = remain[0]
            tr = remain[1]
            bd = ""
        elif len(remain) == 3:
            tl = remain[0]
            tr = remain[1]
            bd = remain[2]
        else:
            # 不符合预期，但尽量容错
            tl, tr, bd = "", "", ""

        # suffix解析尺寸、材质、O型圈
        second_dash = suffix.find("-")
        left_size = suffix[:second_dash]
        right_part = suffix[second_dash+1:]

        # O型圈
        if right_part.endswith("OR"):
            oring = "OR"
            right_part = right_part[:-2]
        else:
            oring = ""

        # 材质
        if right_part.endswith("BR"):
            material_ = "BR"
            right_size = right_part[:-2]
        elif right_part.endswith("SS"):
            material_ = "SS"
            right_size = right_part[:-2]
        else:
            material_ = ""
            right_size = right_part

        return jt, tl, tr, bd, left_size, right_size, material_, oring

    jt, tl, tr, bd, sl, sr, mat, oring = extract_details(raw_code)

    # 规则处理
    # 1. 当tl == tr时，无论bd是否存在，都合并成一个螺纹类型字母
    #   原则：JJ -> J，同时保留bd，如JJ4 -> J4
    #   尺寸如果两端都有且不同，进行从小到大排序
    if tl == tr and tl != "":
        # 合并螺纹类型
        # 原：tl=J, tr=J -> tl=J, tr=""
        tr = ""
        # 同时保持bd不变

        # 尺寸排序
        # 如果都有尺寸值，则对sl,sr进行从小到大排序（按数值）
        if sl and sr:
            # 转int进行排序
            try:
                sizes = [int(sl), int(sr)]
                sizes.sort()
                sl, sr = str(sizes[0]), str(sizes[1])
            except:
                # 如果异常(非纯数字)，则按字符串排序
                strs = [sl, sr]
                strs.sort()
                sl, sr = strs[0], strs[1]

    # 如果螺纹类型不同且需要排序按字母进行（已有逻辑），则保持
    # （题中需求重点在相同螺纹类型的情况，这里逻辑不变）
    if tr != "" and tl != tr:
        combo = [(tl, sl), (tr, sr)]
        combo.sort(key=lambda x: x[0])
        tl, sl = combo[0]
        tr, sr = combo[1]

    # 重建final_code
    thread_part = tl
    if tr:
        thread_part += tr
    if bd:
        thread_part += bd

    # 尺寸部分动态添加
    # 根据sl,sr来确定如何添加"-"
    size_part = ""
    if sl and sr:
        if sl == sr:
            size_part = "-" + sl  # 去掉重复的端口编码
        else:
            size_part = "-" + sl + "-" + sr
    elif sl:
        size_part = "-" + sl
    # 若都无，不添加尺寸

    final_code = jt + thread_part + size_part + mat + oring
    return final_code


@app.route("/", methods=["GET","POST"])
def index():
    selected_values = {
        "joint_type": "",
        "bend_type": "",
        "thread_type_left": "",
        "thread_size_left": "",
        "thread_type_right": "",
        "thread_size_right": "",
        "material_type": "",
        "o_ring": ""
    }
    result = None

    if request.method == "POST":
        selected_values["joint_type"] = request.form.get("joint_type", "")
        selected_values["bend_type"] = request.form.get("bend_type", "")
        selected_values["thread_type_left"] = request.form.get("thread_type_left", "")
        selected_values["thread_size_left"] = request.form.get("thread_size_left", "")
        selected_values["thread_type_right"] = request.form.get("thread_type_right", "")
        selected_values["thread_size_right"] = request.form.get("thread_size_right", "")
        selected_values["material_type"] = request.form.get("material_type", "")
        selected_values["o_ring"] = request.form.get("o_ring", "")

        result = process_code(selected_values["joint_type"],
                              selected_values["bend_type"],
                              selected_values["thread_type_left"],
                              selected_values["thread_size_left"],
                              selected_values["thread_type_right"],
                              selected_values["thread_size_right"],
                              selected_values["material_type"],
                              selected_values["o_ring"])

    return render_template("index.html",
                           joint_types=joint_types,
                           thread_types=thread_types,
                           bend_types=bend_types,
                           material_types=material_types,
                           thread_size_map=thread_size_map,
                           result=result,
                           selected=selected_values)


if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True)
# 2024 成都固佰特科技有限公
